//实例化Vue对象
var app = new Vue({
    el: '#app',
    data: {
        load: false,     // 加载动画
        nowTime: '',     // 时间
        revive_data: [   // 回收数据
            { id: 1, img: "h", data: 0, title: '回收量(kg)'},  
            { id: 2, img: "c", data: 0, title: '参与人数(人)'}, 
            { id: 3, img: "l", data: 0, title: '领袋数量(个)'},
            { id: 4, img: "s", data: 0, title: '生活垃圾量(kg)'}
        ],
        delivery_data: [],
        dump: ['js', 'zl', 'sl', 'zw', 'bl'], // 回收垃圾列表
        // '金属', '纸类', '塑料', '织物', '玻璃'

        countList: [], // 回收量列表
        count: [
            { name: '今日回收数量', data: 0 },
            { name: '累计回收总数', data: 0 },
            { name: '户均回收量'  , data: 0 }
        ],
        allCount: 0,
        allDay: 0,

        right: [],  // 正确率
        addPoints:  0, // 新增积分
        onLineShop: 0, // 兑换积分
        count_img: [], // 分类图片
        url: 'http://120.26.94.63:8000/api/ckScreen/',    // 线上接口
        // url: 'http://192.168.0.21:8101/api/ckScreen/',    // 本地接口
        
        p: 0,

        key: [],
        key_: {
            provid: null,
            cityid: null,
            distid: null,
            strtid: null,
            commid: null,
            comminid: null
        },

        centerDialogVisible: false, // 模态框

        full: false, // 屏幕加载
        // 无限级联
        area: { 
            checkStrictly: true,
            lazy: true,
            lazyLoad (node, resolve) {
            setTimeout(() => {
              const { level } = node;
              if(level==0) {
                axios.get(`http://120.26.94.63:8000/api/sysOrg/1`).then(res=>{
                    const nodes = res.data.data.map(item => ({
                        value: item.id,
                        label: item.name,
                        leaf: node.level >= 2
                    }));
                    resolve(nodes);// 通过调用resolve将子节点数据返回，通知组件数据加载完成
                  })
              }else {
                axios.get(`http://120.26.94.63:8000/api/sysOrg/${node.value}`).then(res=>{
                    const nodes = res.data.data
                    .map(item => ({
                        value: item.id,
                        label: item.name,
                        leaf: item.count==0
                    }));
                    resolve(nodes);// 通过调用resolve将子节点数据返回，通知组件数据加载完成
                  })
              }
              
             }, 300);
            }
        },

        //* echarts配置 *//
        // 饼图
        option_consumption: {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                icon: "roundRect",
                itemWidth: 15,   // 设置图例图形的宽
                itemHeight: 7,
                orient: 'vertical',
                itemGap: 10,

                left: -5,
                y: 'center',
                data: ['线上消费', '线下设备消费', '线下商城消费'],
                textStyle: {
                    color: '#fff',
                    fontSize: 8
                }
            },
            color: ['#B721FF', '#FF709A', '#12BDFF'],
            series: [
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['80%', '50%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        // position: 'center'
                    },
                    emphasis: {
                        label: { show: false,} // 内部文字提示
                    },
                    labelLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(0,0,0,0)',
                            width: 2
                        }
                    },
                    data: [
                        { value: 335, name: '线上消费' },
                        { value: 310, name: '线下设备消费' },
                        { value: 234, name: '线下商城消费' },

                    ]
                }
            ]
        },

        // 仪表盘
        option_correct: {
            series: [
                {
                    // name: "业务指标",
                    type: "gauge",
                    center: ["50%", "60%"],
                    radius: "80%", //仪表大小
                    min: 0,
                    max: 100,
                    startAngle: 210, //开始角度
                    endAngle: -30, //结束角度
                    data: [{ value: 50, name: "" }],
                    axisLine: {
                        // show: false,
                        lineStyle: { // 属性lineStyle控制线条样式
                            color: [
                                [0.2, '#3DC44A'],
                                [0.8, '#419AF2'],
                                [1, '#B14430'],
                            ],
                            // shadowColor: "#eee",
                            // shadowBlur: 10,
                            width: 2
                        }
                    },
                    splitLine: {
                        length: 10,
                        lineStyle: {            // 分隔线样式。
                            color: "auto",   //线的颜色,默认 #eee。
                            width: 2
                        }
                    },
                    axisLabel: {            // 坐标轴小标记
                        textStyle: {
                            fontSize: 5,    //改变仪表盘内刻度数字的大小
                        }
                    },
                    axisTick: {
                        show: false
                    },

                    pointer: { //指针样式
                        length: '35%',
                        width: 1,
                    },
                    title: {
                        // show:true,
                        offsetCenter: [0, '40vh'],
                        color: '#fff',
                        fontSize: 10
                    },
                    detail: {
                        show: false,
                    },
                },

            ]
        },

        //* hightCharts配置 *//

        // 3D柱状图
        circle:{
            chart: {
                type: 'cylinder',
                backgroundColor: 'rgba(0,0,0,0)',
                options3d: {
                    enabled: true,
                    alpha: 15,
                    beta: 0,   	      // 横向旋转 
                    depth: 0,         // 深度
                    viewDistance: 100
                },
            },
            title: {text: ''},
            xAxis: {
                type: "category",
                labels: {
                    style: {
                        color: '#fff',
                        fontSize: '1vh'
                    }
                },
                gridLineWidth: 0, //纵向网格线宽度
            },
            credits: {
                enabled: false  //隐藏highCharts.com标识
            },
            yAxis: {
                gridLineWidth: 1, //横向网格线宽度
                gridLineColor: 'rgba(0,0,0,0)',
                labels: '1233',
                enabled: true
            },
            plotOptions: {
                series: {
                    depth: 30,   // 圆柱宽度
                    colorByPoint: false,
                    dataLabels: { //显示柱形上方的文字标签
                        color: "#fff",
                        enabled: true,
                        defer: 100,
                        y: -10
                    },
                }
            },
            series: [ {
                name: '垃圾分类数',
                data: [
                    { name: '', y: 10 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                ],
                showInLegend: false
            }]

        },

        // 3D环形图
        Ring: {
            chart: {
                type: 'pie',
                backgroundColor: 'rgba(0,0,0,0)',
                options3d: {
                    enabled: true,
                    alpha: 70,
                    color: '#fff'
                }
            },
            title: {text: '',},
            plotOptions: {
                pie: {
                    innerSize: '50%',
                    depth: '50',
                    dataLabels: { enabled: false, }
                }
            },
            credits: {
                enabled: false  //隐藏highCharts.com标识
            },
            colors: ['rgba(0,255,255,.6)', 'rgba(18,189,255,.6)'],
            series: [{
                name: '分类比例',
                data: [
                    ['已参与', 0],
                    ['未参与', 0],

                ]
            }]
        },

        // 折线图
        line: {
            title: {
                useHTML: true,
                text: '<div style="font-size: 1vh;color: #fff">回收重量<span style="color: #999">(kg)</span></div>',
                align: 'left',
            }, // 标题
            legend: {enabled: false},  // 图例隐藏
            credits: {enabled: false}, //隐藏highCharts.com标识
            xAxis: {
                name: 'kg',
                tickWidth: 0,   //去掉刻度
                type: "category",
                categories: [],
                gridLineColor: 'rgba(0,0,0,0)',
                labels: {
                    style: {
                        color: '#fff',
                        fontSize: '1vh'
                    }
                },
                gridLineWidth: 1, //纵向网格线宽度
            },
            yAxis: {
                name: '时间',
                gridLineWidth: 1, //横向网格线宽度
                gridLineColor: 'rgba(0,0,0,0)',
                enabled: true,
            },
            series: [
                {name: '易腐', data: [], color: '#49D78A'},
                {name: '其他', data: [], color: '#F2BF0C'}
            ],
            
            chart: {backgroundColor: 'rgba(0,0,0,0)'},
        },

        // 地图
        map: {
            backgroundColor: 'rgba(0,0,0,.1)',
            title: {
                text: '当前服务地区',
                left: 'center',
                textStyle: {
                    color: '#fff'
                },
            },
            //地理坐标系组件用于地图的绘制，支持在地理坐标系上绘制散点图，线集。
            //要显示散点图，必须填写这个配置
            bmap:{
                show:true,
                roam: true, //是否允许鼠标滚动放大，缩小
                map:'china',
                center: [120.22221, 30.2084],
                aspectScale: 0.75, //长宽比
                zoom:10,
                mapStyle: {//地图样式
                    'styleJson': [
                      {
                        'featureType': 'water',
                        'elementType': 'all',
                        'stylers': {
                          'color': '#17568C'
                        }
                      },
                      {
                        'featureType': 'land',
                        'elementType': 'geometry',
                        'stylers': {
                          'color': '#030A3A'
                        }
                      },
                      {
                        'featureType': 'highway',
                        'elementType': 'all',
                        'stylers': {
                          'visibility': 'off'
                        }
                      },
                      {
                        'featureType': 'arterial',
                        'elementType': 'geometry.fill',
                        'stylers': {
                          'color': '#000000'
                        }
                      },
                      {
                        'featureType': 'arterial',
                        'elementType': 'geometry.stroke',
                        'stylers': {
                          'color': '#0b3d51'
                        }
                      },
                      {
                        'featureType': 'local',
                        'elementType': 'geometry',
                        'stylers': {
                          'color': '#000000'
                        }
                      },
                      {
                        'featureType': 'railway',
                        'elementType': 'geometry.fill',
                        'stylers': {
                          'color': '#000000'
                        }
                      },
                      {
                        'featureType': 'railway',
                        'elementType': 'geometry.stroke',
                        'stylers': {
                          'color': '#08304b'
                        }
                      },
                      {
                        'featureType': 'subway',
                        'elementType': 'geometry',
                        'stylers': {
                          'lightness': -70
                        }
                      },
                      {
                        'featureType': 'building',
                        'elementType': 'geometry.fill',
                        'stylers': {
                          'color': '#000000'
                        }
                      },
                      {
                        'featureType': 'all',
                        'elementType': 'labels.text.fill',
                        'stylers': {
                          'color': '#857f7f'
                        }
                      },
                      {
                        'featureType': 'all',
                        'elementType': 'labels.text.stroke',
                        'stylers': {
                          'color': '#000000'
                        }
                      },
                      {
                        'featureType': 'building',
                        'elementType': 'geometry',
                        'stylers': {
                          'color': '#022338'
                        }
                      },
                      {
                        'featureType': 'green',
                        'elementType': 'geometry',
                        'stylers': {
                          'color': '#062032'
                        }
                      },
                      {
                        'featureType': 'boundary',
                        'elementType': 'all',
                        'stylers': {
                          'color': '#465b6c'
                        }
                      },
                      {
                        'featureType': 'manmade',
                        'elementType': 'all',
                        'stylers': {
                          'color': '#022338'
                        }
                      },
                      {
                        'featureType': 'label',
                        'elementType': 'all',
                        'stylers': {
                          'visibility': 'off'
                        }
                      }
                    ]
                  },
                label: {  //图形上的文本标签，可用于说明图形的一些数据信息
                    show:true,  //是否显示文本
                    color:'#fff',  //文本颜色
                },
                itemStyle: { //地图区域的多边形 图形样式。 默认样试。
                    areaColor: '#323c48', //地图区域的颜色。
                    // borderColor: '#f00', //边框线
                    normal:{
                        borderColor: '#0ff', //边框线
                        areaColor: {
                            type: 'radial',
                            x: 0.5,
                            y: 0.5,
                            r: 0.8,
                            colorStops: [{
                                offset: 0,
                                color: '#030945' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#0ff'  // 100% 处的颜色
                            }],
                            globalCoord: true // 缺省为 false
                            }
                    }
                },
                emphasis:{ //高亮状态下的多边形和标签样式。
                    label:{ //文本
                        color: '#fff',
                    },
                    itemStyle:{ //区域
                        areaColor: {
                            type: 'radial',
                            x: 0.5,
                            y: 0.5,
                            r: 0.8,
                            colorStops: [{
                                offset: 0,
                                color: '#030945' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#0ff'  // 100% 处的颜色
                            }],
                            globalCoord: true // 缺省为 false
                            },
                            borderColor:'#0ff',
                            borderWidth:'2'
                    }
                }
            },
            tooltip:{
                show:true,
            },
            series:[
                {
                    type: 'effectScatter', //样试
                    coordinateSystem:'bmap', //该系列使用的坐标系
                    data:[],
                    itemStyle: { //样试。
                        normal:{ //默认样试
                            color: '#ff0'
                        }
                    },
                    label: {
                        normal: {
                            // formatter: '{b}',
                            formatter: '',
                            position: 'right',
                            show: true
                        }
                    },
                    //标记的大小,可以设置数组或者函数返回值的形式
                    symbolSize: function (val) {
                        return val[2] / 25; // 除以缩小倍数
                    },
                    rippleEffect: { //涟漪特效相关配置。
                        brushType: 'stroke' //波纹的绘制方式
                    },
                    hoverAnimation: true, //鼠标移入放大圆
                    
                }
            ]
        },
    

        g: 0



    },
    watch: {
        // 长数据规范
        addPoints(n,o) {
            if(this.g==2)return
            switch (this.g) {
                case 0: {
                    n = (n/10000).toFixed(2);
                    this.g = 1
                    this.addPoints = n+'万'
                }
                case 1: {
                    n = (n/10000).toFixed(2);
                    this.g = 2
                    this.addPoints = n+'亿'
                }
                default: console.log('err');
            }
        },
        onLineShop(n,o) {
            if(n>100000000) {
                n = (n/100000000).toFixed(2);
                this.g = 2
                this.onLineShop = n+'亿'
            }

            if(n>10000) {
                n = (n/10000).toFixed(2);
                    this.g = 1
                    this.onLineShop = n+'万'
            }
            
        },

    },
    
    methods: {
        // 请求封装
        request(url,params) {
            return axios({
                method: 'get',
                url: this.url+url,
                params: params
            }).then(res=> {
                let a = Object.keys(res.data.data)
                if(res.data.data==null)return res.data.message
                return res.data.data[`${a}`]
            }).catch(err=> {
                console.log(err);
                return err.data.message
            })
        },

        // 获取全部数据
        async getData() {
            // const loading = this.$loading({
            //     lock: true,
            //     text: 'Loading',
            //     spinner: 'el-icon-loading',
            //     background: 'rgba(0, 0, 0, 0.7)'
            // });
            let result = await this.request('getComprehensive',this.key_)
            console.log('allData:',result);
            if(typeof result == 'string')return
            this.regeneration(result[0])
            this.getNum(result[4])
            this.getPhotoAddress(result[1])
            this.delivery(result[2])
            this.cellComparison(result[3])
            this.thisMonth(result[5])
            this.integral(result[6])
            this.trend(result[7])
            this.amap(result[8])
            // 启动实时更新(参数为秒)
            this.update(40) 
            // setTimeout(() => {
            //     loading.close();
            // }, 1500);
            
        },
        // 搜索
        search() {
            this.centerDialogVisible = false
            console.log(this.key);
            this.key_.provid = this.key[0]
            this.key_.cityid = this.key[1]
            this.key_.distid = this.key[2]
            this.key_.strtid = this.key[3]
            this.key_.commid = this.key[4]
            this.key_.comminid = this.key[5]
            
            this.getData()
            
        },
        // 填充再生资源数据
        regeneration(data) {
            console.log('再生资源',data);
            let revive = this.revive_data
            revive[0].data = data.recyclable
            revive[1].data = data.participate
            revive[2].data = data.collarTimes
            revive[3].data = data.householdGarbage
        },
        // 填充回收量
        getNum(data) {
            console.log('回收量',data);
            let list = [1,2,3,4,5]
            let allCount = 0
            let allDay = 0
            data.map(item=> {
                allCount += (item.weight*100)
                allDay += (item.weightDay*100)
                item.typeId=="1026"?list[0]=item:''
                item.typeId=="4"?list[1]=item:''
                item.typeId=="2"?list[2]=item:''
                item.typeId=="1017"?list[3]=item:''
                item.typeId=="1121"?list[4]=item:''
            })
            console.log('1111111111111111111111111111111111111',data);
            this.allCount = (allCount/100).toFixed(2)
            this.allDay = (allDay/100).toFixed(2)
            

            this.countList = list
            console.log('2222222222222222222222222222222222222',list);  
            // 回收量初始化
            this.count[0].data = list[0].weightDay
            this.count[1].data = list[0].weight
            this.count[2].data = list[0].households
        },
        // 幻灯片切换（回收量切换）
        swch(index) {
            let list = this.countList
            console.log(list,'111111111111')
            this.count[0].data = list[index].weightDay
            this.count[1].data = list[index].weight
            this.count[2].data = list[index].households
        },

        // 填充投放记录
        delivery(data) {
            console.log('投放记录',data);
            if(this.p==1&&data.length==0){
                this.delivery_data=[];
                clearInterval(w);
                return;
            }
            
            // 格式化数据
            data.map((item,index)=> {
                item.time = item.time.substring(0,10)
                switch(item.type) {
                    case '1026':data[index].type = '铁类';break;
                    case '1017':data[index].type = '旧衣物';break;
                    case '11':data[index].type = '易腐垃圾';break;
                    case '12':data[index].type = '可回收垃圾';break;
                    case '13':data[index].type = '其他垃圾';break;
                    case '14':data[index].type = '有毒有害';break;
                    case '2':data[index].type = '塑料类';break;
                    case '4':data[index].type = '纸类';break;
                    case '1121':data[index].type = '玻璃';break;
                    case '17':data[index].type = '小家电';break;
                    default: item.type
                }
            })
            
            this.delivery_data = data
            window.len = this.delivery_data.length-4
            if(data.length==0)return
            // 第一次获取到不为空的值时进行滚动
            if(this.p==0) {
                this.p=1
                // 配置项
                let i=0;                    // 已滚动次数
                let start = 16              // 初始高度（初始展示条数*每条高度）
                let h = 4                 // 每次滚动距离（与每条高度一致）
                let time = 1600              // 滚动时间间隔
                var firstTr = document.querySelector('.body>table')  // 容器节点
                //*********************//
                // firstTr.style.height = start+'vh'
                if(this.p==0){def=1000}
                function q() { // 高度增加，向下滚动
                    let length = window.len  // 实时获取应滚动次数(减去的num为初始展示条数)
                    if(length<=0)return
                    if(i<length) {
                        var qq = setTimeout(()=> {
                            // firstTr.style.height = start+h*i+'vh'
                            firstTr.style.transform = `translateY(${h*i}vh)`
                            i++
                            q()
                            clearTimeout(qq)
                        },time)
                        
                    }else {
                        w()
                    }
                    
                    
                }
                
                function w() {  // 高度减小，向上滚动
                    if(i!==0) {
                        let ww = setTimeout(()=> {
                            // firstTr.style.height = start+h*i+'vh'
                            firstTr.style.transform = `translateY(${h*i}vh)`
                            i--
                            w()
                            clearTimeout(ww)
                        },time)
                    }else {
                        q() // 此时i再次为0
                    }
                    
                }

                q()
            }

             
        },

        // 填充小区对比数据 + h_柱状绘图
        cellComparison(data) {
            console.log('小区对比',data);
            if(this.p==1 && data.length == 0) {
                this.circle.series[0].data = [
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                    { name: '', y: 0 },
                ]
                Highcharts.chart('circle', this.circle) 
            }
            this.p = 1
            
            let shit = this.circle.series[0].data
            data.forEach((item1 ,index)=> {
                console.log(index);
                shit[index].name = item1.communityName
                shit[index].y    = Number(item1.rate)
            });  

            // 圆柱渐变
            let colors = ['rgba(12,96,255,.4)', '#17ABFF'];
            Highcharts.getOptions().colors = Highcharts.map(colors, function (color) {
                return {
                    radialGradient: { cx: 0, cy: -.8, r: 6 },
                    stops: [[0, color], [2, Highcharts.Color(color).brighten(140).get('rgb')] // darken 
                    ]
                };
            });
            // 绘图
            Highcharts.chart('circle', this.circle)  
        },

        // 填充趋势数据 + h_折线图
        trend(data) {
            console.info('垃圾趋势',data)
            let result1 = []
            let result2 = []
            let day = []
            data.map(item=> {
                result1.push(Number(item.weight))
                result2.push(Number(item.otherWeight))
                var m = item.time.slice(5,7)
                var d = item.time.slice(8,10)
                day.push(m+'/'+d)
            })
            this.line.series[0].data = result1
            this.line.series[1].data = result2
            this.line.xAxis.categories = day
            console.log(123,this.line);
            // 绘图
            Highcharts.chart('line', this.line)
        },

        // 填充正确率参与率 + e_仪表绘图 + h_环形绘图
        thisMonth(data) {
            console.info('正确率参与率',data)
        // echarts 正确率赋值
            let correct = this.option_correct.series[0].data[0]
            let correct1 = echarts.init(document.getElementById('correct1'));
            let correct2 = echarts.init(document.getElementById('correct2'));
            correct.value = data.monthCorrect*100
            correct1.setOption(this.option_correct); // 绘仪表1
            
            
            correct.value = data.thisMonthCorrect*100
            correct2.setOption(this.option_correct);  // 绘仪表2
            

        // hightcharts参与率赋值
            let Ring = this.Ring.series[0].data
            Ring[0][1] = data.monthParticipate*100
            Ring[1][1] = Math.round((1-data.monthParticipate)*100)
            Highcharts.chart('participate1', this.Ring) // 绘环形1

            Ring[0][1] = data.thisMonthParticipate*100
            Ring[1][1] = Math.round((1-data.thisMonthParticipate)*100)
            Highcharts.chart('participate2', this.Ring) // 绘环形2
        },
        // 填充图片
        getPhotoAddress(data) {
            console.info('分类图片',data)
            this.count_img = data
        },
        // 积分消费 + e_饼图
        integral(data) {
            let consumption = this.option_consumption.series[0].data
            console.info('积分消费',data)
            this.addPoints = data.addPoints
            this.onLineShop = data.onLineShop
            consumption[0].value = data.onLineShop
            consumption[1].value = data.OfflineDevice
            consumption[2].value = data.OfflineShop                

            // 绘图
            let Consumption = echarts.init(document.getElementById('consumption'))
            Consumption.setOption(this.option_consumption); // 饼图
        },

        // 实时数据更新
        update(time) {
            time*=1000
            setTimeout(() => {
                this.getData()
            }, time);
        },

        // 右上角计时器
        timer() {
            setInterval(() => {
                this.nowTime = this.clearTime();
            }, 1000);
        },

        // 格式化时间
        clearTime(w) {
            if (w) { var date = new Date(w * 1000) } else { var date = new Date() }
            let y = date.getFullYear()
            let m = date.getMonth() + 1
            m = m < 10 ? '0' + m : m
            let d = date.getDate()
            d = d < 10 ? ('0' + d) : d
            let h = date.getHours()
            h = h < 10 ? ('0' + h) : h
            let mi = date.getMinutes()
            mi = mi < 10 ? ('0' + mi) : mi
            let s = date.getSeconds()
            s = s < 10 ? ('0' + s) : s
            var now = y + '-' + m + '-' + d + ' ' + h + ':' + mi + ':' + s
            return now
        },

        // 地图组件
        async amap(data) {
            console.log('map:',data);
            let result = []
            data.map((item,index)=> {
                let child = {name: '', value:['','']}
                child.name = item.commName
                child.value[0] = Number(item.mapX)
                child.value[1] = Number(item.mapY)
                child.value[2] = 200
                result.push(child)
            })
            this.map.series[0].data = result
            let Consumption = echarts.init(document.getElementById('map'))
            Consumption.setOption(this.map); // 绘图
            return true
        },

        // 打开弹窗
        Hbtn() {
            console.log('1111111')
            this.centerDialogVisible = true
        },
    },
    
    created() { // 初始化完成钩子
        this.timer() // 开启计时器
        this.getData() // 获取全部数据
    }
})

